import datetime
import os
import sys
import atexit
from selenium import webdriver
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
from selenium.webdriver.support.wait import WebDriverWait


def singleton(cls):
    """单例模式装饰器"""
    _instance = {}

    def wrapper(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]

    return wrapper


@singleton
class EdgeDriver:
    def __init__(self):
        # 手动指定Edge驱动路径
        self.driver_path = r"D:\Edge驱动\edgedriver_win64\msedgedriver.exe"
        self.driver = None
        self.init_driver()

    def init_driver(self):
        """初始化Edge浏览器驱动"""
        # 校验驱动路径是否存在
        if not os.path.exists(self.driver_path):
            raise FileNotFoundError(f"Edge驱动文件不存在：{self.driver_path}")

        # 配置Edge浏览器选项
        edge_options = Options()
        edge_options.add_argument("--remote-allow-origins=*")
        edge_options.add_argument("--disable-blink-features=AutomationControlled")  # 隐藏自动化标识
        edge_options.add_argument("--start-maximized")  # 窗口最大化

        # 创建驱动实例
        self.driver = webdriver.Edge(
            service=Service(self.driver_path),
            options=edge_options
        )

        # 设置隐式等待
        self.driver.implicitly_wait(5)

        # 注册程序退出时自动关闭驱动
        atexit.register(self.quit_driver)

    def GetScreenShot(self, custom_name=""):
        """
        屏幕截图功能
        :param custom_name: 自定义截图名称后缀（可选）
        """
        try:
            # 构建截图保存路径（适配不同操作系统）
            base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../images"))
            dirname = datetime.datetime.now().strftime("%Y-%m-%d")
            save_dir = os.path.join(base_dir, dirname)

            # 确保文件夹存在
            os.makedirs(save_dir, exist_ok=True)

            # 生成截图文件名
            time_str = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
            caller_name = sys._getframe().f_back.f_code.co_name  # 调用函数名
            filename = f"{caller_name}-{time_str}"
            if custom_name:
                filename += f"-{custom_name}"
            filename += ".png"

            # 保存截图
            save_path = os.path.join(save_dir, filename)
            self.driver.save_screenshot(save_path)
            print(f"截图成功，保存路径：{save_path}")
            return save_path
        except Exception as e:
            print(f"截图失败：{str(e)}")
            return None

    def ClearInput(self, element):
        actions = ActionChains(self.driver)
        actions.click(element)  # 点击元素
        actions.key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL)  # Ctrl+A
        actions.send_keys(Keys.DELETE)  # 删除
        actions.perform()  # 执行所有动作

    def quit_driver(self):
        """安全关闭浏览器驱动"""
        if hasattr(self, "driver") and self.driver:
            try:
                self.driver.quit()
                print("Edge浏览器已安全关闭")
            except Exception as e:
                print(f"关闭浏览器失败：{str(e)}")


# 创建单例实例
QESDriver = EdgeDriver()
